package com.compmov.socialnetwork;

import java.io.File;
import java.io.IOException;

import com.compmov.datamodel.Comentario;
import com.compmov.datamodel.Foto;
import com.compmov.datamodel.Lugar;
import com.compmov.datamodel.LugarAgregado;
import com.compmov.datamodel.Persona;
import com.compmov.datamodel.TipoLugar;
import com.compmov.webservice.ComentarioWSClient;
import com.compmov.webservice.FotoWSClient;
import com.compmov.webservice.LugarAgregadoWSClient;
import com.compmov.webservice.WSClientException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddImages extends Activity {
	private String path;
	private TextView indicador;	
	private String urlFoto="";	
	private Uri outputFileUri;
	private double longitude=0;
	private double latitude=0;
	private int id;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_image);
		path = Environment.getExternalStorageDirectory() + "/";
		indicador =(TextView)findViewById(R.id.mensaje);

		Bundle extras = getIntent().getExtras();
		id =Integer.valueOf( extras.getString("id_lugar"));

	}

	
	public void cancel(View v) {
		finish();
	}

	public void capturar(View v) {
		urlFoto = Environment.getExternalStorageDirectory().getAbsolutePath()
		+ "/TEMP.jpg";

		File file = new File(urlFoto);
		//if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				Log.e("WEBSERVICE",e.getMessage(),e);
			}
		//}
		
		outputFileUri=Uri.fromFile(file);

		Intent intent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
		startActivityForResult(intent, 1);
	}

	public void galeria(View v) {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, path), 2);
	}




	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode==0){
			Toast notificacionToast = Toast.makeText(getApplicationContext(),
					"La imagen no pudo se cargada", Toast.LENGTH_SHORT);
			notificacionToast.show();
			return;
		}

		switch (requestCode) {
		case 1:
			try {

				ContentResolver cr = getApplicationContext()
				.getContentResolver();
				Cursor c = cr.query(outputFileUri, new String[] {
						MediaStore.Images.ImageColumns.DATA,
						MediaStore.Images.ImageColumns.LATITUDE,
						MediaStore.Images.ImageColumns.LONGITUDE }, null, null,
						null);

				if (c != null) {
					c.moveToFirst();
					latitude = c
					.getDouble(c
							.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.LATITUDE));
					longitude = c
					.getDouble(c
							.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.LONGITUDE));

				} else {
					try {
						LocationManager lm = (LocationManager) this
						.getSystemService(Context.LOCATION_SERVICE);
						Criteria crit = new Criteria();
						crit.setAccuracy(Criteria.ACCURACY_FINE);
						String provider = lm.getBestProvider(crit, true);
						Location loc = lm.getLastKnownLocation(provider);
						latitude = loc.getLatitude();
						longitude = loc.getLongitude();
					} catch (Exception ex) {
					}
				}

			} catch (Exception e) {
				Toast notificacionToast = Toast.makeText(getApplicationContext(),
						"Error en captura. Intente de nuevo", Toast.LENGTH_SHORT);
				notificacionToast.show();
				return;
			}




			indicador.setText("Imagen obtenida de la Camara");

			break;

		case 2:
			Uri uri = data.getData();

			ContentResolver cr = getApplicationContext()
			.getContentResolver();

			try{
				Cursor c = cr.query(uri, new String[] {
						MediaStore.Images.ImageColumns.DATA,
						MediaStore.Images.ImageColumns.LATITUDE,
						MediaStore.Images.ImageColumns.LONGITUDE }, null, null,
						null);


				if (c != null) {
					c.moveToFirst();
					latitude =c.getDouble(c
							.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.LATITUDE));
					longitude = c.getDouble(c
							.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.LONGITUDE));

					if(latitude==0 && longitude==0){
						Toast notificacionToast = Toast.makeText(getApplicationContext(),
								"La imagen no tiene geolocalizacion", Toast.LENGTH_SHORT);
						notificacionToast.show();
						return;
					}
					urlFoto=getPath(uri);

					indicador.setText("Imagen obtenida de la Galeria");
				}else{
					Toast notificacionToast = Toast.makeText(getApplicationContext(),
							"La imagen no tiene geolocalizacion", Toast.LENGTH_SHORT);
					notificacionToast.show();
					break;
				}

			}catch(Exception ex){

				Toast notificacionToast = Toast.makeText(getApplicationContext(),
						"La imagen no tiene geolocalizacion", Toast.LENGTH_SHORT);
				notificacionToast.show();

			}

			break;

		}


	}

	public void add(View v){
		
		if(urlFoto.length()==0){
			Toast notificacionToast = Toast.makeText(getApplicationContext(),
					"Por favor suba una foto", Toast.LENGTH_SHORT);
			notificacionToast.show();
			return;
		}		
			
		Persona persona=com.compmov.libraries.Utils.getPersona();
		Lugar lugar=new Lugar(id,"","",0.0,0.0,0,"");
		FotoWSClient foto=new FotoWSClient("fotos");
		Foto pic=new Foto(0,urlFoto,persona,lugar);

		try{
			Log.d("WEBSERVICE", pic.toString());
			pic =foto.subirFoto(pic);
			Toast.makeText(getBaseContext(),"Foto agregada exitosamente",
					Toast.LENGTH_SHORT).show();
			this.finish();
			
		} catch (WSClientException e) {
			Toast.makeText(getBaseContext(),"Error en el servidor. Intente de nuevo",
					Toast.LENGTH_SHORT).show();
			return;
		}

	}
	
	/**
	 * Extrae el path desde un URI
	 * 
	 * @param uri
	 * @return
	 */
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

}